define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	ins = {}
	
	search = ()->
		# Lower case the query key for couchdb and parse through PostalCode and Phone format 
		_query = $('[name="search_term"]', ins).val().toLowerCase().isPostal().isPhone()

		# If the query is in format LASTNAME, FIRSTNAME.. remove the space after the comma to match the indexing
		(_query = _query.replace(/[ ]/g, '') if _query.charAt(i+1) is " " ) if (i = _query.indexOf(',')) isnt 0

		arg =
			search_term: _query,
			search_type: $('input:checked', ins).val().toLowerCase()

		$.publish "mb.query", arg

	$.fn.mb_search = (S) ->
		ins = @
		$this = $(@)

		$('input:[name="reset"]', @).on 'click', ->
			$('[name="search_term"]', ins).val("")

		$(':radio', @).on "change", ->
			search()

		$('form', @).on 'submit', -> return false

		$('input:submit', @).on 'click', ->
			search()
			return false
		return @
	return
